package com.example.x50.untils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer implements Runnable {
        int port;
        Socket socket;
        public TcpServer(int port) {
        this.port=port;
        }
        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(port);
                this.socket  = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                while (true) {

                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream(),true);
                    String data = in.readLine();
                    FileIO.write(data);
                    if (data.equals("exit")) {
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }



